package com.ccubee.data.transfer;

import com.ccubee.data.transfer.properties.DataProperties;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.task.TaskExecutor;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * canal 上下文
 *
 * @Author ycf
 * @Date 2022/5/22 00:20
 * @Version 1.0
 */
@AllArgsConstructor
public class CanContext implements ApplicationContextAware, DisposableBean {
    private final static Map<String, CanalConnectorWork> CANAL_CONNECTOR_MAP = new HashMap<>(4);
    private DataProperties dataProperties;
    private TaskExecutor taskExecutor;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        if (Objects.isNull(dataProperties.getCanal())) {
            return;
        }
        dataProperties.getCanal().getInstance().forEach((k, v) -> taskExecutor.execute(() -> {
            CanalConnectorWork canalConnectorWork = new CanalConnectorWork(dataProperties, k, v);
            CANAL_CONNECTOR_MAP.put(k, canalConnectorWork);
        }));

    }

    @Override
    public void destroy() {
        CANAL_CONNECTOR_MAP.forEach((k, v) -> v.disconnect());
    }
}
